package com.wwu.system.service.impl;

import com.wwu.common.web.ResultPage;
import com.wwu.system.service.IOnlineUserService;
import com.wwu.system.entity.SysUser;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 在线用户服务接口实现类
 * @author 一蓑烟雨
 * @version 1.0.0
 * @date 2023-07-26 16:14
 */
@Service
public class OnlineUserImpl implements IOnlineUserService  {
    @Resource
    private SessionRegistry sessionRegistry;

    /**
     * 分页查询在线用户信息
     * @param pageNum  页码
     * @param pageSize  每页数量
     * @param userName  用户名
     * @param loginIp   登陆地址
     * @return com.wwu.common.web.ResultPage<com.wwu.system.entity.SysUser>
     * @author 一蓑烟雨
     * @date 2023/7/26 16:20
     */
    @Override
    public ResultPage<SysUser> getOnlineUserListPage(Integer pageNum, Integer pageSize, String userName, String loginIp) {
        List<Object> principals = sessionRegistry.getAllPrincipals();
        List<SysUser> userList = new ArrayList<>();
        for (Object principal: principals) {
            if(principal instanceof SysUser){
                SysUser sysUser = (SysUser) principal;

                if(!StringUtils.hasText(userName)||userName.equals(sysUser.getUsername())){
                    if((!StringUtils.hasText(loginIp) || loginIp.equals(sysUser.getLoginIp()))){
                        //getAllSessions方法的第二个参数为false表示不包含过期会话
                        List<SessionInformation> allSessions = sessionRegistry.getAllSessions(sysUser, false);
                        for(SessionInformation sessionInformation: allSessions){
                            sysUser.setSessionId(sessionInformation.getSessionId());
                            userList.add(sysUser);
                        }
                    }
                }
            }
        }
        return new ResultPage<>(userList.size(),userList);
    }

    /**
     * 踢出登陆用户
     * @param sessionIds 会话id
     * @return int
     * @author 一蓑烟雨
     * @date 2023/7/26 16:20
     */
    @Override
    public int pickOutUser(List<String> sessionIds) {
        int count = 0;
        if (!ObjectUtils.isEmpty(sessionIds)){
            for (String sessionId: sessionIds) {
                SessionInformation information = sessionRegistry.getSessionInformation(sessionId);
                if (information != null) {
                    //立即过期
                    information.expireNow();
                    //移除Session
                    sessionRegistry.removeSessionInformation(sessionId);
                    count++;
                }
            }
        }

        return count;
    }
}
